import akshare as ak
from MyTT import MyTT
from retry import retry

from python_quant.common.common import ths_billboard


def ths_valuation_invest():
    """
    同花顺价值股
    """
    url = 'https://eq.10jqka.com.cn/open/api/hot_list/v1/investment/value_invest.txt'
    return ths_billboard(url)


def low_baidu_valuation(code):
    """
    低估值标的
    """
    pb_df = ak.stock_zh_valuation_baidu(symbol=code, indicator="市净率")
    pb_percent = get_baidu_valuation_percent(pb_df)
    pe_df = ak.stock_zh_valuation_baidu(symbol=code, indicator="市盈率(TTM)")
    pe_percent = get_baidu_valuation_percent(pe_df)
    ps_df = ak.stock_zh_valuation_baidu(symbol=code, indicator="市现率")
    ps_percent = get_baidu_valuation_percent(ps_df)
    if pb_percent < 0 and pe_percent < 0 and ps_percent < 0:
        return True
    return False


def get_baidu_valuation_percent(stock_zh_valuation_baidu_df):
    """
    低估百分位
    """
    values = stock_zh_valuation_baidu_df['value'].values
    ma_values = MyTT.MA(values, len(values))
    mid_high_value = max(values) / 2
    min_value = min(mid_high_value, ma_values[-1])
    percent = (values[-1] - min_value) / min_value * 100
    return percent


def valuation_to_code_list(code_list):
    """
    整合低估值标的
    """
    percent_list = list()
    for code in code_list:
        is_true = low_baidu_valuation(code)
        if is_true:
            percent_list.append(code)
    return percent_list


@retry(tries=10, delay=10, backoff=1)
def valuation_stocks(code_list):
    """
    估值面
    """
    return valuation_to_code_list(code_list)
